<script setup>
import { ref, onMounted } from 'vue'
import { getUserListAPI, updateUserStatusAPI } from '@/api/user'

// 搜索表单数据
const searchForm = ref({
  username: ''
})

// 分页相关 - 固定每页13条数据
const currentPage = ref(1)
const pageSize = ref(13)
const total = ref(0)
const tableData = ref([])
const loading = ref(false)

// 切换用户状态
const handleToggleStatus = async (row) => {
  const action = row.status === 1 ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(
      `确定要${action}用户 "${row.username || '微信用户'}" 吗？`,
      `${action}确认`,
      {
        confirmButtonText: `确定${action}`,
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用接口修改状态
    await updateUserStatusAPI(row.id, row.status === 1 ? 0 : 1)
    row.status = row.status === 1 ? 0 : 1
    ElMessage.success(`${action}成功`)
  } catch (error) {
    // 用户取消操作不提示，操作失败才提示
    if (error !== 'cancel') {
      ElMessage.error(`${action}失败`)
      console.error(error)
    }
  }
}

// 点击搜索按钮时筛选用户名
const handleSearch = () => {
  currentPage.value = 1
  getUserList()
}

// 重置搜索条件
const handleReset = () => {
  searchForm.value = {
    username: ''
  }
  currentPage.value = 1
  getUserList()
}

// 当前页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  getUserList()
}

// 获取用户列表
const getUserList = async () => {
  if (loading.value) return

  try {
    loading.value = true
    const res = await getUserListAPI(
      currentPage.value,
      pageSize.value,
      searchForm.value.username
    )

    const responseData = res.data.data || {}
    tableData.value = responseData.records || []
    total.value = responseData.total || 0
  } catch (error) {
    ElMessage.error('获取用户列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 页面挂载时获取用户列表
onMounted(() => {
  getUserList()
})
</script>

<template>
  <div class="user-management">
    <div class="page-header">
      <h1>用户管理</h1>
    </div>

    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%"
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="用户名" min-width="120">
        <template #default="scope">
          {{ scope.row.username || '微信用户' }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="注册时间" min-width="160" />
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button
            size="small"
            :type="row.status === 1 ? 'warning' : 'success'"
            @click="handleToggleStatus(row)"
          >
            {{ row.status === 1 ? '禁用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.user-management {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h1 {
      font-size: 1.5rem;
      color: #1a202c;
      margin: 0;
    }
  }

  .search-bar {
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>
